using System;
using System.IO;
using System.Threading;
using Limestone.Storage.XML;
using NUnit.Framework;

namespace Limestone.Test
{
    public class TestBase
    {
        protected const string BasePagePath = @"c:\temp\limestone\pages";
        protected const string BaseTemplatePath = @"c:\temp\limestone\templates";
        protected const string BaseTrashcanPath = @"c:\temp\limestone\trashcan";

        [SetUp]
        public void CleanUp()
        {
            ClearFolder(BasePagePath);
            ClearFolder(BaseTemplatePath);
            ClearFolder(BaseTrashcanPath);
        }

        protected static IPageProvider GetPageProvider()
        {
            return new PageProvider(GetStorage(), GetCurrentUserId(), new PageStubCache(GetStorage()));
        }

        protected static IGetCurrentUserId GetCurrentUserId()
        {
            return new GetCurrentUserFromFake("Henke");
        }

        protected static IStorage GetStorage()
        {
            return new XmlStorage(GetXmlCfg(), GetCurrentUserId());
        }

        protected static ITemplateProvider GetTemplateProvider()
        {
            var getCurrentUserId = new GetCurrentUserFromFake("Henke");
            return new TemplateProvider(new XmlStorage(GetXmlCfg(), getCurrentUserId));
        }

        protected static IPageStubCache GetPageStubCache()
        {
            return new PageStubCache(GetStorage());
        }

        protected static IXmlStorageConfig GetXmlCfg()
        {
            return new XmlStorageConfig
            {
                BasePagePath = BasePagePath,
                BaseTemplatePath = BaseTemplatePath,
                BaseTrashcanPath = BaseTrashcanPath
            };
        }

        protected static void ClearFolder(string folderName)
        {
            var dir = new DirectoryInfo(folderName);

            foreach (var fi in dir.GetFiles())
            {
                try
                {
                    fi.Delete();
                }
                catch (Exception)
                {
                }

            }

            foreach (var di in dir.GetDirectories())
            {
                ClearFolder(di.FullName);
                try
                {
                    di.Delete(true);
                }
                catch (Exception)
                {
                }
            }
        }
    }
}